﻿using System;
using System.Xml;
using System.Net;
using System.IO;

namespace tomvangaever.library.WS
{
    public static class WSHelper
    {
        public static string Invoke(string url,string action, string soap) {
            // Create webrequest object with default credentials
            HttpWebRequest webRequest = CreateWebRequest(url, action);
            webRequest.UseDefaultCredentials = true;
            
            //Add SoapEnvelope to webrequest if needed
            if (!string.IsNullOrEmpty(soap))
            {
                XmlDocument soapEnvelopeXml = CreateSoapEnvelope(soap);
                InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
            }
            else {
                webRequest.ContentLength = 0;
            }

            // begin async call to web request.
            IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);

            // suspend this thread until call is complete. You might want to
            // do something usefull here like update your UI.
            asyncResult.AsyncWaitHandle.WaitOne();

            // get the response from the completed web request.
            string soapResult;
            using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
            using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
            {
                soapResult = rd.ReadToEnd();
            }

            return soapResult;
        }

        private static HttpWebRequest CreateWebRequest(string url, string action)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            if(!string.IsNullOrEmpty(action)) webRequest.Headers.Add("SOAPAction", action);
            webRequest.ContentType = "text/xml;charset=\"utf-8\"";
            webRequest.Accept = "text/xml";
            webRequest.Method = "POST";
            return webRequest;
        }

        private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
        {
            using (Stream stream = webRequest.GetRequestStream())
            {
                soapEnvelopeXml.Save(stream);
            }
        }

        private static XmlDocument CreateSoapEnvelope(string content)
        {
            XmlDocument soapEnvelopeXml = new XmlDocument();
            soapEnvelopeXml.LoadXml(content.ToString().Trim());
            return soapEnvelopeXml;
        }

    }
}
